package eraikikon;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

import javax.swing.table.AbstractTableModel;

import com.mysql.jdbc.util.ResultSetUtil;
/**
 * Taula datu base bateko datuekin betetzeko.
 * @author SI3taldea
 *
 */
public class ResultSetTableModel extends AbstractTableModel {
	private Connection connection;

	private Statement statement;

	private ResultSet resultSet;

	private ResultSetMetaData metaData;

	private int numberOfRows;

	// keep track of database connection status
	private boolean connectedToDatabase = false;

	/**
	 * Datu basearen drivera kargatu eta konexioa ezartzen du.
	 * 
	 * @param driver
	 * @param url
	 * @param username
	 * @param password
	 * @param query
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public ResultSetTableModel(String driver, String url, String username,
			String password, String query) throws SQLException,
			ClassNotFoundException {
		// load database driver class
		Class.forName(driver);
		// connect to database
		connection = DriverManager.getConnection(url, username, password);
		// create Statement to query database
		statement = connection.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
		// update database connection status
		connectedToDatabase = true;
		// set query and execute it
		setQuery(query);
	} // end constructor ResultSetTableModel
	// set new database query string

	/**
	 * SQL agindua(query) esleitzen du
	 */
	public void setQuery(String query) throws SQLException,
			IllegalStateException {
		// ensure database connection is available
		if (!connectedToDatabase)
			throw new IllegalStateException("Not Connected to Database");
		// specify query and execute it
		resultSet = statement.executeQuery(query);
		// obtain meta data for ResultSet
		metaData = resultSet.getMetaData();
		// determine number of rows in ResultSet
		resultSet.last(); // move to last row
		numberOfRows = resultSet.getRow(); // get row number
		// notify JTable that model has changed
		fireTableStructureChanged();
	} // end method setQuery
	// get class that represents column type
/**
 * Pasatako zutabearen klasea(izena) bueltatzen du.
 */
	public Class getColumnClass(int column) throws IllegalStateException {
		// ensure database connection is available
		if (!connectedToDatabase)
			throw new IllegalStateException("Not Connected to Database");
		// determine Java class of column
		try {
			String className = metaData.getColumnClassName(column + 1);
			// return Class object that represents className
			// System.out.println(className);
			if ("java.sql.Timestamp".equals(className))
				className="java.lang.String";
			
			return Class.forName(className);
		} // end try
		catch (Exception exception) {
			exception.printStackTrace();
		} // end catch
		return Object.class; // if problems occur above, assume type Object
	} // end method getColumnClass
	// get number of columns in ResultSet
/**
 * SQL aginduko emaitzaren zutabe kopurua bueltatzen du.
 * 
 */
	public int getColumnCount() throws IllegalStateException {
		// ensure database connection is available
		if (!connectedToDatabase)
			throw new IllegalStateException("Not Connected to Database");
		// determine number of columns
		try {
			return metaData.getColumnCount();
		} // end try
		catch (SQLException sqlException) {
			sqlException.printStackTrace();
		} // end catch
		return 0; // if problems occur above, return 0 for number of columns
	} // end method getColumnCount
	// get name of a particular column in ResultSet

	/**
	 * Adierazitako zutabearen atributuaren izena bueltatzen du.
	 */
	public String getColumnName(int column) throws IllegalStateException {
		// ensure database connection is available
		if (!connectedToDatabase)
			throw new IllegalStateException("Not Connected to Database");
		// determine column name
		try {
			return metaData.getColumnName(column + 1);
		} // end try
		catch (SQLException sqlException) {
			sqlException.printStackTrace();
		} // end catch
		return ""; // if problems, return empty string for column name
	} // end method getColumnName
	// return number of rows in ResultSet
	/**
	 * SQL aginduko emaitzaren errenkada kopurua bueltatzen du.
	 * 
	 */
	public int getRowCount() throws IllegalStateException {
		// ensure database connection is available
		if (!connectedToDatabase)
			throw new IllegalStateException("Not Connected to Database");
		return numberOfRows;
	} // end method getRowCount
	// obtain value in particular row and column
/**
 * Errenkada eta zutabea emanda posizio horretan dagoen objektua bueltatzen du.
 */
	public Object getValueAt(int row, int column) throws IllegalStateException {
		// ensure database connection is available
		if (!connectedToDatabase)
			throw new IllegalStateException("Not Connected to Database");
		// obtain a value at specified ResultSet row and column
		try {
			resultSet.absolute(row + 1);
			if (column == 0){
				String aux = resultSet.getString(column+1);
				aux = aux.substring(0, aux.length()-2);
				return aux;
			}
			
			return resultSet.getObject(column + 1);
		} // end try
		catch (SQLException sqlException) {
			sqlException.printStackTrace();
		} // end catch
		return ""; // if problems, return empty string object
	} // end method getValueAt
	// close Statement and Connection
/**
 * Datu basearekin deskonexioa ahalbidetzen du.
 */
	public void disconnectFromDatabase() {
		if (!connectedToDatabase)
			return;
		// close Statement and Connection
		try {
			statement.close();
			connection.close();
		} // end try
		catch (SQLException sqlException) {
			sqlException.printStackTrace();
		} // end catch
		finally // update database connection status
		{
			connectedToDatabase = false;
		} // end finally
	} // end method disconnectFromDatabase
}
